// pages/order/order/order.js
var api = require('../../../api/api.js');
const pay = require('../../../services/pay.js');
const hms = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: ["全部", "待付款", "待发货", "待收货", "已完成"],
    userInfo: wx.getStorageSync("userInfo"),
    currentTab: 0,
    status: 5,
    orders: [],
    page: 1,
    pageSize: 12,
    hasMoreData: true,
    hiddenPay: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var status = options.status;
    if (status == 0) {
      that.setData({
        currentTab: 1
      })
    }
    if (status == 1) {
      that.setData({
        currentTab: 2
      })
    }
    if (status == 2) {
      that.setData({
        currentTab: 3
      })
    }
    if (status == 5) {
      that.setData({
        currentTab: 0
      })
    }
    that.setData({
      status: status
    })
    that.getOrderList(status);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  navbarTap: function (e) {
    let that = this;
    that.setData({
      page: 1
    })
    if (e.currentTarget.id == 0) {
      that.setData({
        status: 5
      })
      that.getOrderList(0);
      that.getCurrentTab(e.currentTarget.offsetLeft, e.currentTarget.id)
    }
    if (e.currentTarget.id == 1) {
      that.setData({
        status: 0
      })
      that.getOrderList();
      that.getCurrentTab(e.currentTarget.offsetLeft, e.currentTarget.id)
    }
    if (e.currentTarget.id == 2) {
      that.setData({
        status: 1
      })
      that.getOrderList();
      that.getCurrentTab(e.currentTarget.offsetLeft, e.currentTarget.id)
    }
    if (e.currentTarget.id == 3) {
      that.setData({
        status: 2
      })
      that.getOrderList();
      that.getCurrentTab(e.currentTarget.offsetLeft, e.currentTarget.id)
    }
    if (e.currentTarget.id == 4) {
      that.setData({
        status: 3
      })
      that.getOrderList();
      that.getCurrentTab(e.currentTarget.offsetLeft, e.currentTarget.id)
    }
  },

  getCurrentTab: function (offsetLeft, id) {
    let that = this;
    that.setData({
      sliderOffset: offsetLeft,
      currentTab: id
    });
  },

  getOrderList: function () {
    let that = this;
    wx.showLoading({
      title: '加载中...',
    });
    wx.request({
      url: api.OrderList,
      data: {
        page: that.data.page,
        per_page: 12,
        status: that.data.status,
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function(res) {
        var ordersListTmp = that.data.orders;
        if (res.data.error_code == 0) {
          if (that.data.page == 1) {
            ordersListTmp = [];
          }
          for (var i = 0; i < res.data.orders.length; i++) {
            res.data.orders[i].created_at = hms.toFormatTime(res.data.orders[i].created_at * 1000, 'Y-M-D h:m')
          }
          if (res.data.orders.length < that.data.pageSize) {
            that.setData({
              orders: ordersListTmp.concat(res.data.orders),
              hasMoreData: false,
            });
          } else {
            that.setData({
              orders: ordersListTmp.concat(res.data.orders),
              hasMoreData: true,
              page: that.data.page + 1,
            });
          }
        }
      }
    })
    setTimeout(function () {
      wx.hideLoading();
    }, 300);
  },

  toShopTap: function() {
    wx.redirectTo({
      url: '/pages/category/category/category',
    })
  },

  toOrderDetailTap: function(e) {
    let that = this;
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      // url: '/pages/order/orderDetail/orderDetail?id=' + id,
      url: '/pages/payResult/payResult?status=1&orderId=' + id
    })
  },

  toPDFTap: function() {
    wx.showToast({
      title: '订单PDF',
      image: '/images/icon/icon_error.png'
    })
  },

  //付款
  toPayTap: function(e) {
    let that = this;
    var index = e.currentTarget.dataset.index;
    that.setData({
      hiddenPay: false,
      index: index
    });
  },

  wxPayTap: function(e) {
    let that = this;
    var index = parseInt(that.data.index);
    var orderId = that.data.orders[index].id;
    wx.showLoading({
      "mask": true,
      title: '支付中...'
    });
    pay.payOrder(parseInt(orderId)).then(res => {
      wx.redirectTo({
        url: '/pages/payResult/payResult?status=1&orderId=' + orderId
      });
    }).catch(res => {
      wx.showToast({
        title: '支付失败',
        image: '/images/icon/icon_error.png'
      })
    });
    wx.hideLoading();
    that.setData({
      hiddenPay: true
    })
  },

  yuePayTap: function() {
    let that = this;
    var index = parseInt(that.data.index);
    var orderId = that.data.orders[index].id;
    var userMoney = that.data.userInfo.money;
    var total = that.data.orders[index].total;
    if (parseInt(userMoney) < parseInt(total)) {
      wx.showToast({
        title: '余额不足',
        image: '/images/icon/icon_error.png'
      })
    } else {
      wx.showLoading({
        "mask": true,
        title: '支付中...'
      });
      wx.request({
        url: api.PaymentOrder,
        data: {
          order: parseInt(orderId),
          code: "balance.pay"
        },
        header: {
          'Content-Type': 'application/json',
          'X-bocang-Authorization': wx.getStorageSync('token')
        },
        method: "POST",
        success: function (res) {
          if (res.data.error_code == 0) {
            wx.showToast({
              title: "支付成功",
              icon: 'success'
            });
            setTimeout(function () {
              wx.hideLoading();
            }, 1000);
            wx.redirectTo({
              url: '/pages/order/order/order?status=' + 5,
            })
          }
        }
      })
    }
    that.setData({
      hiddenPay: true
    })
  },

  //隐藏付款弹窗
  closePopupTap: function () {
    this.setData({
      hiddenPay: true
    })
  },

  //取消订单
  toCancelTap: function(e) {
    let that = this;
    var orderId = e.currentTarget.dataset.id;
    wx.showLoading({
      title: '取消中...',
    });
    wx.request({
      url: api.OrderCancel,
      data: {
        order: orderId,
        reason: "1"
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function(res) {
        if (res.data.error_code == 0) {
          wx.showToast({
            title: '取消成功',
            icon: "success"
          })
          that.setData({
            page: 1
          })
          that.getOrderList();
        }
      },
      fail: function(res) {
        wx.showToast({
          title: '取消失败',
          image: "/images/error.png"
        })
      }
    });
    setTimeout(function () {
      wx.hideLoading();
    }, 300);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that = this;
    that.setData({
      page: 1
    })
    that.getOrderList();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;
    // 页面上拉触底事件的处理函数
    if (that.data.hasMoreData) {
      that.getOrderList();
    } else {
      wx.showToast({
        title: '没有更多数据',
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})